package link.doublyCircularLinkedListSentinel;

import link.doublyLinkedListSentinel.DoublyLinkedListSentinel;

import java.util.Iterator;

/**
 * @author czt
 * @version 1.0
 * @since 2024/12/12
 */
public class DoublyCircularLinkedListSentinel implements Iterable<Integer>{

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = sentinel.next;
            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    private static class Node {
        // 前指针
        Node prev;

        // 值
        int value;

        // 后指针
        Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    private Node sentinel = new Node(null, -1, null);

    public DoublyCircularLinkedListSentinel() {
        sentinel.next = sentinel;
        sentinel.prev = sentinel;
    }

    /**
     * 给第一个位置添加节点
     * @param value 节点值
     */
    public void addFirst(int value) {
        // 原来的头节点
        Node head = sentinel.next;

        // 待插入节点
        Node node = new Node(sentinel, value, head);
        sentinel.next = node;
        head.prev = node;
    }

    /**
     * 给最后一个位置添加节点
     * @param value 节点值
     */
    public void addLast(int value) {
        // 原来的尾节点
        Node tail = sentinel.prev;

        Node node = new Node(tail, value, sentinel);

        tail.next = node;

        sentinel.prev = node;
    }

    /**
     * 删除头节点
     */
    public void removeFirst() {
        // 获取头节点
        Node head = sentinel.next;
        if (head == sentinel) {
            throw new RuntimeException("不能删除哨兵节点");
        }
        // 使哨兵的next指向head的next
        sentinel.next =head.next;
        // 使head.next的prev指向哨兵
        head.next.prev = sentinel;
    }

    /**
     * 删除尾节点
     */
    public void removeLast() {
        // 获取尾节点
        Node tail = sentinel.prev;
        if (tail == sentinel) {
            throw new RuntimeException("不能删除哨兵节点");
        }
        sentinel.prev = tail.prev;
        tail.prev.next = sentinel;
    }
}
